{% extends "base.html" %}

{% block content %}
<div class="bg-white rounded-lg shadow-card p-6 mb-6">
  <h2 class="text-xl font-bold mb-4 flex items-center">
    <i class="fa fa-cogs text-primary mr-2"></i> 设备管理
  </h2>
  
  <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
    <div class="relative w-full md:w-64 mb-4 md:mb-0">
      <input type="text" id="search-device" placeholder="搜索设备..." 
        class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
      <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
    </div>
    
    <div class="flex space-x-3">
      <button id="add-device-btn" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-custom">
        <i class="fa fa-plus mr-2"></i> 新增设备
      </button>
    </div>
  </div>
  
  <div class="overflow-x-auto">
    <table class="min-w-full divide-y divide-gray-200">
      <thead class="bg-gray-50">
        <tr>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备名称</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前库存</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">单位</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
        </tr>
      </thead>
      <tbody class="bg-white divide-y divide-gray-200" id="devices-table-body">
        {% for device in devices %}
        <tr class="hover:bg-gray-50 transition-custom">
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="flex items-center">
              <div class="ml-4">
                <div class="text-sm font-medium text-gray-900">{{ device.name }}</div>
              </div>
            </div>
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="text-sm text-gray-900">{{ device.quantity }}</div>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            {{ device.unit }}
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
            <button data-id="{{ device.id }}" data-name="{{ device.name }}" data-quantity="{{ device.quantity }}" data-unit="{{ device.unit }}" class="edit-btn text-indigo-600 hover:text-indigo-900 mr-3 transition-custom">
              <i class="fa fa-pencil mr-1"></i> 编辑
            </button>
            <button data-id="{{ device.id }}" data-name="{{ device.name }}" class="delete-btn text-red-600 hover:text-red-900 transition-custom">
              <i class="fa fa-trash mr-1"></i> 删除
            </button>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  
  <div class="flex items-center justify-between px-4 py-3 sm:px-6 mt-4">
    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
      <div>
        <p class="text-sm text-gray-700">
          显示第 <span class="font-medium">1</span> 至 <span class="font-medium">{{ devices|length }}</span> 条，共 <span class="font-medium">{{ total_devices }}</span> 条记录
        </p>
      </div>
      <div>
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
            <span class="sr-only">上一页</span>
            <i class="fa fa-chevron-left h-5 w-5"></i>
          </a>
          <a href="#" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white hover:bg-primary/90">
            1
          </a>
          <a href="#" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
            2
          </a>
          <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
            ...
          </span>
          <a href="#" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
            8
          </a>
          <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
            <span class="sr-only">下一页</span>
            <i class="fa fa-chevron-right h-5 w-5"></i>
          </a>
        </nav>
      </div>
    </div>
  </div>
</div>

<!-- 新增/编辑设备模态框 -->
<div id="device-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
    <div class="flex justify-between items-center p-6 border-b">
      <h3 class="text-lg font-medium text-gray-900" id="modal-title">新增设备</h3>
      <button id="close-modal" class="text-gray-400 hover:text-gray-500">
        <i class="fa fa-times text-xl"></i>
      </button>
    </div>
    <div class="p-6">
      <form id="device-form">
        <div class="mb-4">
          <label for="device-name" class="block text-sm font-medium text-gray-700 mb-1">设备名称</label>
          <input type="text" id="device-name" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" placeholder="请输入设备名称" required>
        </div>
        <div class="mb-4">
          <label for="device-quantity" class="block text-sm font-medium text-gray-700 mb-1">初始库存</label>
          <input type="number" id="device-quantity" name="quantity" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" placeholder="请输入初始库存" required>
        </div>
        <div class="mb-4">
          <label for="device-unit" class="block text-sm font-medium text-gray-700 mb-1">单位</label>
          <input type="text" id="device-unit" name="unit" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" placeholder="请输入单位（如：个、台、箱等）" required>
        </div>
      </form>
    </div>
    <div class="flex justify-end p-6 border-t">
      <button id="cancel-modal" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all duration-200">
        取消
      </button>
      <button id="save-device" class="ml-3 px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all duration-200">
        保存
      </button>
    </div>
  </div>
</div>

<!-- 删除确认模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0" id="delete-modal-content">
    <div class="p-6">
      <div class="text-center">
        <i class="fa fa-exclamation-triangle text-4xl text-yellow-500 mb-4"></i>
        <h3 class="text-lg font-medium text-gray-900 mb-2">确认删除</h3>
        <p class="text-gray-500 mb-6" id="delete-message">您确定要删除该设备吗？此操作不可撤销。</p>
      </div>
      <div class="flex justify-center space-x-4">
        <button id="cancel-delete" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all duration-200">
          取消
        </button>
        <button id="confirm-delete" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all duration-200">
          确认删除
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  // 搜索功能
  document.getElementById('search-device').addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('#devices-table-body tr');
    
    rows.forEach(row => {
      const deviceName = row.querySelector('td:first-child div div').textContent.toLowerCase();
      if (deviceName.includes(searchTerm)) {
        row.style.display = '';
      } else {
        row.style.display = 'none';
      }
    });
  });

  // 模态框相关变量
  const deviceModal = document.getElementById('device-modal');
  const modalContent = document.getElementById('modal-content');
  const deleteModal = document.getElementById('delete-modal');
  const deleteModalContent = document.getElementById('delete-modal-content');
  const deviceForm = document.getElementById('device-form');
  const modalTitle = document.getElementById('modal-title');
  let currentDeviceId = null;

  // 打开新增设备模态框
  document.getElementById('add-device-btn').addEventListener('click', function() {
    modalTitle.textContent = '新增设备';
    deviceForm.reset();
    currentDeviceId = null;
    openModal(deviceModal, modalContent);
  });

  // 打开编辑设备模态框
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const deviceId = this.getAttribute('data-id');
      const name = this.getAttribute('data-name');
      const quantity = this.getAttribute('data-quantity');
      const unit = this.getAttribute('data-unit');
      
      currentDeviceId = deviceId;
      modalTitle.textContent = '编辑设备';
      
      document.getElementById('device-name').value = name;
      document.getElementById('device-quantity').value = quantity;
      document.getElementById('device-unit').value = unit;
      
      openModal(deviceModal, modalContent);
    });
  });

  // 打开删除确认模态框
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const deviceId = this.getAttribute('data-id');
      const deviceName = this.getAttribute('data-name');
      currentDeviceId = deviceId;
      document.getElementById('delete-message').textContent = `您确定要删除设备 "${deviceName}" 吗？此操作不可撤销。`;
      openModal(deleteModal, deleteModalContent);
    });
  });

  // 关闭模态框
  document.getElementById('close-modal').addEventListener('click', function() {
    closeModal(deviceModal, modalContent);
  });

  document.getElementById('cancel-modal').addEventListener('click', function() {
    closeModal(deviceModal, modalContent);
  });

  document.getElementById('cancel-delete').addEventListener('click', function() {
    closeModal(deleteModal, deleteModalContent);
  });

  // 保存设备
  document.getElementById('save-device').addEventListener('click', function() {
    if (deviceForm.checkValidity()) {
      const formData = new FormData(deviceForm);
      const data = Object.fromEntries(formData.entries());
      
      // 根据是否有 currentDeviceId 判断是新增还是编辑
      const action = currentDeviceId ? '编辑' : '新增';
      
      // 这里应该发送API请求，这里简化为模拟
      console.log(`${action}设备:`, data);
      
      // 模拟成功后刷新页面
      setTimeout(() => {
        closeModal(deviceModal, modalContent);
        showToast(`${action}设备成功`);
        // 实际项目中应该在这里更新表格数据，而不是刷新页面
        // window.location.reload();
      }, 500);
    } else {
      deviceForm.reportValidity();
    }
  });

  // 确认删除
  document.getElementById('confirm-delete').addEventListener('click', function() {
    // 这里应该发送API请求，这里简化为模拟
    console.log('删除设备:', currentDeviceId);
    
    // 模拟成功后刷新页面
    setTimeout(() => {
      closeModal(deleteModal, deleteModalContent);
      showToast('删除设备成功');
      // 实际项目中应该在这里从表格中移除该行，而不是刷新页面
      window.location.reload();
    }, 500);
  });

  // 打开模态框动画
  function openModal(modal, content) {
    modal.classList.remove('hidden');
    setTimeout(() => {
      content.classList.remove('scale-95', 'opacity-0');
      content.classList.add('scale-100', 'opacity-100');
    }, 10);
  }

  // 关闭模态框动画
  function closeModal(modal, content) {
    content.classList.remove('scale-100', 'opacity-100');
    content.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
      modal.classList.add('hidden');
    }, 300);
  }

  // 显示提示消息
  function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-0 opacity-0';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
      toast.classList.remove('opacity-0');
      toast.classList.add('opacity-100');
    }, 10);
    
    setTimeout(() => {
      toast.classList.remove('opacity-100');
      toast.classList.add('opacity-0');
      setTimeout(() => {
        document.body.removeChild(toast);
      }, 300);
    }, 3000);
  }
</script>
{% endblock %}